/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cmp.player.controls;

import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;

/**
 * Controls behaviour of bullets.  like how fast it is and stuff like that.
 * @author krummer
 */
public class BulletControl extends AbstractControl {
    private float lifeTime;
    private float bulletSpeed;
    private Vector3f bulletTarget;
    private Node collisionNode;
    private boolean homing;
    private boolean moving;
    private RigidBodyControl body;
    
    @Override
    public void setSpatial(Spatial spatial) {
        super.setSpatial(spatial);
        this.lifeTime = 3.f;
        this.bulletSpeed = 10.f;
        this.bulletTarget = null;
        this.collisionNode = null;
        this.homing = false;
        this.moving = false;
        this.body = spatial.getControl(RigidBodyControl.class);
    }
    
    public void setHoming(boolean home) {
        this.homing = home;
    }
    
    public void setLifeTime(float time) {
        this.lifeTime = time;
    }
    
    public void setBulletTarget(Vector3f dir) {
        this.bulletTarget = dir;
    }
    
    public void setCollisionNode(Node col) {
        this.collisionNode = col;
    }
    
    public Node getCollisionNode() {
        return this.collisionNode;
    }
    
    public void remove() {
        this.body.setEnabled(false);
        this.getSpatial().removeFromParent();
    }
    
    private void move() {
        //it has a target and is not moving yet.
        if((this.bulletTarget != null) && !this.moving) {
            Vector3f bulletPos = this.getSpatial().getWorldTranslation();
            Vector3f dir = bulletTarget.subtract(bulletPos);
            dir = dir.normalize();
            this.body.setGravity(Vector3f.ZERO); //not affected by gravity.
            
            this.body.setLinearVelocity(dir.mult(bulletSpeed));
            this.moving = true;
        }
    }

    @Override
    protected void controlUpdate(float tpf) {
        //count lifetime
        if(lifeTime > 0.f ) {
            this.move();
            lifeTime -= tpf;
        } else {
            this.remove();
        }
   
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
        
    }

    public Control cloneForSpatial(Spatial spatial) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    
}
